<script>
import * as echarts from 'echarts'

let energyTypePie = null
let rangePie = null
let timeCarbonEmissions = null
let analysisCarbonEmissionsActivities = null

export default {
  name: 'CarbonEmissionsAnalysis',
  props: {
    queryParams: {
      required: false,
      default: null
    },
    projectList: {
      required: false,
      default: []
    }
  },
  data() {
    return {
      startTime: null,
      endTime: null,
      energyTypePieData: [],
      rangePieData: [],
      dataList: [],
      timeCarbonEmissionsData: [],
      spaceCarbonEmissionsData: [],
      activityCarbonEmissionsData: [],
      activityNames: [],
      activityTotals: []
    }
  },
  computed: {
    getProjectNames() {
      return this.projectList.filter(project => this.queryParams.sceneProjectId == null || project.value === this.queryParams.sceneProjectId)
        .map(project => project.label).join('，')
    },
    getEnergyTypePieDataPercent() {
      return this.energyTypePieData.map(project => project.percent).join('、')
    },
    getMaxEnergyTypePieData() {
      if (this.energyTypePieData.length > 0) {
        return this.energyTypePieData.slice().sort((a, b) => b.value - a.value)[0]
      }
      return {}
    },
    getMinEnergyTypePieData() {
      if (this.energyTypePieData.length > 0) {
        return this.energyTypePieData.slice().sort((a, b) => a.value - b.value)[0]
      }
      return {}
    },
    getRangePieDataPercent() {
      return this.rangePieData.map(project => project.percent).join('、')
    },
    getMaxTimeCarbonEmissionsDataByTotal() {
      if (this.timeCarbonEmissionsData.length > 0) {
        return this.timeCarbonEmissionsData.slice().sort((a, b) => b.total - a.total)[0]
      }
      return {}
    },
    getMinTimeCarbonEmissionsDataByTotal() {
      if (this.timeCarbonEmissionsData.length > 0) {
        return this.timeCarbonEmissionsData.slice().sort((a, b) => a.total - b.total)[0]
      }
      return {}
    },
    getSolidifyDateDate() {
      return this.timeCarbonEmissionsData.map(item => item.solidifyDate)
    }
  },
  watch: {
    queryParams: {
      async handler(val) {
        if (val.sceneProjectId != null) {
          const param = {
            statisticsMode: val.statisticsMode,
            solidifyDateStart: val.startTime,
            solidifyDateEnd: val.endTime,
            sceneProjectId: val.sceneProjectId
          }
          if (val.roomInfo != null && val.roomInfo.length > 0) {
            param.sceneEdificeId = val.roomInfo[0]
            param.sceneFloorId = val.roomInfo.length > 1 ? val.roomInfo[1] : null
            param.sceneRoomId = val.roomInfo.length > 2 ? val.roomInfo[2] : null
          }
          const res = await this.$api.carbonEmissionReport.carbonEmissionsAnalysisTotal(param)
          this.energyTypePieData = res.data.energyTypePieData
          this.rangePieData = res.data.rangePieData
          this.dataList = res.data.dataList
          this.startTime = res.data.startDate
          this.endTime = res.data.endDate

          // 5.2
          console.log("5.2---------")
          const timeCarbonEmissionsRes = await this.$api.carbonEmissionReport.timeCarbonEmissions(param)
          this.timeCarbonEmissionsData = timeCarbonEmissionsRes.data
          const totalList = this.timeCarbonEmissionsData.map(item => item.total)
          let isUp = true
          if (totalList.length > 0) {
            isUp = totalList[0] < totalList[totalList.length - 1]
          }
          this.$emit('isUp', {
            isUp: isUp,
            data: timeCarbonEmissionsRes.data
          })
          // 5.3
          console.log("5.3---------")
          const spaceCarbonEmissions = await this.$api.carbonEmissionReport.spaceCarbonEmissions(param)
          this.spaceCarbonEmissionsData = spaceCarbonEmissions.data

          // 5.4
          console.log("5.4---------")
          const activityCarbonEmissions = await this.$api.carbonEmissionReport.activityCarbonEmissions(param)
          console.log("5.4-----activityCarbonEmissions----")
          this.activityCarbonEmissionsData = activityCarbonEmissions.data.dataList
          this.activityNames = activityCarbonEmissions.data.activityNames
          this.activityTotals = activityCarbonEmissions.data.totals
          // 最后画图
          console.log("initAnalysisCarbonEmissionsTotal---------")
          this.initAnalysisCarbonEmissionsTotal()
        }
      },
      deep: true,
      immediate: true
    }
  },
  destroyed() {
    this.disposeEcharts([energyTypePie, rangePie, timeCarbonEmissions, analysisCarbonEmissionsActivities])
  },
  methods: {
    getProjectNameByProjectId(projectId) {
      const project = this.projectList.find(project => project.value === projectId)
      return project ? project.label : null
    },
    getMaxTimeCarbonEmissionsDataById(id) {
      if (this.timeCarbonEmissionsData.length > 0) {
        return this.timeCarbonEmissionsData.slice().sort((a, b) => b[id] || 0 - a[id] || 0)[0]
      }
      return {}
    },
    getMinTimeCarbonEmissionsDataById(id) {
      if (this.timeCarbonEmissionsData.length > 0) {
        return this.timeCarbonEmissionsData.slice().sort((a, b) => a[id] || 0 - b[id] || 0)[0]
      }
      return {}
    },
    getMaxSpaceCarbonEmissionsDataById(id) {
      if (this.spaceCarbonEmissionsData.length > 0) {
        return this.spaceCarbonEmissionsData.slice().sort((a, b) => b[id] || 0 - a[id] || 0)[0]
      }
      return {}
    },
    getMinSpaceCarbonEmissionsDataById(id) {
      if (this.spaceCarbonEmissionsData.length > 0) {
        return this.spaceCarbonEmissionsData.slice().sort((a, b) => a[id] || 0 - b[id] || 0)[0]
      }
      return {}
    },
    getActivityValueMaxIndex() {
      if (this.activityTotals.length > 0) {
        return this.activityTotals.findIndex((value, index, arr) => {
          return value === Math.max.apply(Math, arr)
        })
      }
      return -1
    },
    getActivityValueMinIndex() {
      if (this.activityTotals.length > 0) {
        return this.activityTotals.findIndex((value, index, arr) => {
          return value === Math.min.apply(Math, arr)
        })
      }
      return -1
    },
    getActivityValueMaxByIndex(index) {
      if (this.activityCarbonEmissionsData.length > 0) {
        const valueList = this.activityCarbonEmissionsData.map(item => item.valueList[index])
        const findIndex = valueList.findIndex((value, index, arr) => {
          return value === Math.max.apply(Math, arr)
        })
        return this.activityCarbonEmissionsData[findIndex]
      }
      return {}
    },
    getActivityValueMinByIndex(index) {
      if (this.activityCarbonEmissionsData.length > 0) {
        const valueList = this.activityCarbonEmissionsData.map(item => item.valueList[index])
        const findIndex = valueList.findIndex((value, index, arr) => {
          return value === Math.min.apply(Math, arr)
        })
        return this.activityCarbonEmissionsData[findIndex]
      }
      return {}
    },
    disposeEcharts(echarts) {
      echarts.forEach((item) => {
        if (item != null) {
          item.dispose()
        }
      })
    },
    initAnalysisCarbonEmissionsTotal() {
      this.disposeEcharts([energyTypePie, rangePie, timeCarbonEmissions, analysisCarbonEmissionsActivities])
      this.$nextTick(() => {
        energyTypePie = echarts.init(document.getElementById('energyTypePie'))
        energyTypePie.setOption({
          title: {
            text: '',
            subtext: '',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '',
              type: 'pie',
              radius: '30%',
              label: {
                formatter: params => {
                  this.$set(this.energyTypePieData[params.dataIndex], 'percent', params.percent + '%')
                  return params.name + ': ' + params.value + '(' + params.percent + '%)'
                }
              },
              data: this.energyTypePieData,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        })
        rangePie = echarts.init(document.getElementById('rangePie'))
        rangePie.setOption({
          title: {
            text: '',
            subtext: '',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '',
              type: 'pie',
              radius: '30%',
              label: {
                formatter: params => {
                  this.$set(this.rangePieData[params.dataIndex], 'percent', params.percent + '%')
                  return params.name + ': ' + params.value + '(' + params.percent + '%)'
                }
              },
              data: this.rangePieData,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        })
        timeCarbonEmissions = echarts.init(document.getElementById('timeCarbonEmissions'))
        timeCarbonEmissions.setOption({
          xAxis: {
            type: 'category',
            data: this.getSolidifyDateDate
          },
          yAxis: {
            type: 'value',
            name: '碳排放量趋势（kgCO2）'
          },
          series: [
            {
              data: this.timeCarbonEmissionsData.map(item => item.total),
              type: 'line'
            }
          ]
        })
        analysisCarbonEmissionsActivities = echarts.init(document.getElementById('analysisCarbonEmissionsActivities'))
        analysisCarbonEmissionsActivities.setOption({
          xAxis: {
            type: 'category',
            axisLabel: {
              rotate: 45
            },
            data: this.activityNames
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: this.activityTotals,
              type: 'bar',
              barWidth: '35%'
            }
          ]
        })
      })
    }
  }
}
</script>

<template>
  <div>
    <h2>05 碳排放情况分析</h2>
    <div class="analysis-box">
      <div>
        <h3>5.1 碳排放总量分析</h3>
        <div class="energy-type-box">
          <div id="energyTypePie" style="width: 700px;height: 300px"></div>
          <div>
            <p style="text-indent: 2em;">
              清晰地展示了场景在特定时间段内不同类型的碳排放量占比。{{ getProjectNames }}在{{ startTime }}-{{ endTime }}，
              碳排放中{{ energyTypePieData.map(item => item.name).join('，') }}的占比分别为
              {{ getEnergyTypePieDataPercent }}。</p>
          </div>
        </div>
        <div class="range-box">
          <div id="rangePie" style="width: 700px;height: 300px"></div>
          <div>
            <p style="text-indent: 2em;">
              清晰地展示了场景在特定时间段内不同范围的碳排放量占比。{{ getProjectNames }}在{{ startTime }}-{{ endTime }}，
              碳排放中{{ rangePieData.map(item => item.name).join('，') }}的占比分别为
              {{ getRangePieDataPercent }}。</p>
          </div>
        </div>
        <table>
          <thead>
          <tr>
            <th>能耗类型</th>
            <th>能耗量</th>
            <th>碳排放量（kgCO2）</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="item in dataList" :key="item.id">
            <td>{{ item.name }}</td>
            <td>{{ item.standardCoal }}</td>
            <td>{{ item.value }}</td>
          </tr>
          <tr>
            <td>合计综合</td>
            <td>
              {{ dataList.map(item => item.standardCoal).reduce((accumulator, currentValue) => accumulator + currentValue, 0).toFixed(2)
              }}
            </td>
            <td>
              {{ dataList.map(item => item.value).reduce((accumulator, currentValue) => accumulator + currentValue, 0).toFixed(2)
              }}
            </td>
          </tr>
          </tbody>
        </table>
        <div class="desc">
          <p>
            展示不同能源在特定时间段内的碳排放情况。{{ getProjectNames }} 在 {{ startTime }}- {{ endTime }}中,
            碳排放中{{ energyTypePieData.map(item => item.name).join('，')
            }}的碳排放量分别为{{ energyTypePieData.map(item => item.value + 'kgCO2').join('，') }}；
            其中{{ getMaxEnergyTypePieData.name }}碳排放量最高，为{{ getMaxEnergyTypePieData.value }} kgCO2；
            {{ getMinEnergyTypePieData.name }}碳排放量最低，为{{ getMinEnergyTypePieData.value }} kgCO2。</p>
        </div>
      </div>
      <div>
        <h3>5.2 时间碳排放</h3>
        <div class="time-carbon-emissions-box">
          <div id="timeCarbonEmissions"
               style="width: 100%;height: 300px;background-color: rgba(2, 149, 144, 0.1);"></div>
          <div>
            <p style="text-indent: 2em;">
              展示在特定时间段内碳排放量的变化趋势。{{ getProjectNames }}在 {{ startTime }}-{{ endTime }}中，
              {{ getMaxTimeCarbonEmissionsDataByTotal.solidifyDate
              }}的碳排放量最高，为{{ getMaxTimeCarbonEmissionsDataByTotal.total }} kgCO2;
              {{ getMinTimeCarbonEmissionsDataByTotal.solidifyDate
              }}碳排放量最低，为{{ getMinTimeCarbonEmissionsDataByTotal.total }} kgCO2。</p>
          </div>
          <table style="width: 100%;margin: 0">
            <thead>
            <tr>
              <th>数据时间</th>
              <th v-for="item in energyTypePieData">{{ item.name }}（kgCO2）</th>
              <th>总量（kgCO2）</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item,index) in timeCarbonEmissionsData" :key="`${item.solidifyDate}_${index}`">
              <td>{{ item.solidifyDate }}</td>
              <td v-for="energyType in energyTypePieData">{{ item[energyType.id] || 0 }}</td>
              <td>{{ item.total }}</td>
            </tr>
            </tbody>
          </table>
          <div>
            <p>展示和分析在时间段内不同能源类型的碳排放量。{{ getProjectNames }}在{{ startTime }}- {{ endTime }}中，
              <span v-for="item in energyTypePieData">
                {{ item.name }}碳排放总量为{{ timeCarbonEmissionsData.map(timeCarbon => timeCarbon[item.id] || 0)
                .reduce((accumulator, currentValue) => accumulator + currentValue, 0) }} kgCO2，
                其中{{ getMaxTimeCarbonEmissionsDataById(item.id).solidifyDate }}的{{ item.name
                }}碳排放量最高，为{{ getMaxTimeCarbonEmissionsDataById(item.id)[item.id] || 0 }} kgCO2;
                {{ getMinTimeCarbonEmissionsDataById(item.id).solidifyDate }}的{{ item.name
                }}碳排放量最低，为 {{ getMinTimeCarbonEmissionsDataById(item.id)[item.id] || 0 }} kgCO2。
              </span>
            </p>
          </div>
        </div>
      </div>
      <div>
        <h3>5.3 空间碳排放</h3>
        <div class="space-carbon-emissions-box">
          <table style="width: 100%;margin: 0">
            <thead>
            <tr>
              <th>所属项目</th>
              <th v-if="queryParams.sceneProjectId != null">所属场景</th>
              <th v-for="item in energyTypePieData">{{ item.name }}（kgCO2）</th>
              <th>总量（kgCO2）</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item,index) in spaceCarbonEmissionsData" :key="`${item.energyTypeName}_${index}`">
              <td>{{ getProjectNameByProjectId(item.sceneProjectId) }}</td>
              <td v-if="queryParams.sceneProjectId != null">{{ item.sceneInfo }}</td>
              <td v-for="energyType in energyTypePieData">{{ item[energyType.id] || 0 }}</td>
              <td>{{ item.total }}</td>
            </tr>
            </tbody>
          </table>
          <div>
            <p v-if="spaceCarbonEmissionsData.length > 0">
              展示和分析在不同场景下不同能源类型的碳排放量。{{ getProjectNames }}在{{ startTime }}-{{ endTime }}中，
              <span v-for="item in energyTypePieData">
                {{ item.name }}碳排放总量为{{ spaceCarbonEmissionsData.map(carbon => carbon[item.id] || 0)
                .reduce((accumulator, currentValue) => accumulator + currentValue, 0) }} kgCO2，
                其中{{ getProjectNameByProjectId(getMaxSpaceCarbonEmissionsDataById(item.id).sceneProjectId) + (getMaxSpaceCarbonEmissionsDataById(item.id).sceneInfo || '')
                }}的{{ item.name
                }}碳排放量最高，为{{ getMaxSpaceCarbonEmissionsDataById(item.id)[item.id] || 0 }} kgCO2;
                {{ getProjectNameByProjectId(getMaxSpaceCarbonEmissionsDataById(item.id).sceneProjectId) + (getMinSpaceCarbonEmissionsDataById(item.id).sceneInfo || '')
                }}的{{ item.name
                }}碳排放量最低，为 {{ getMinSpaceCarbonEmissionsDataById(item.id)[item.id] || 0 }} kgCO2。
              </span>
            </p>
          </div>
        </div>
      </div>
      <div>
        <h3>5.4 活动碳排放统计分析</h3>
        <div class="analysis-carbon-emissions-activities-box">
          <div id="analysisCarbonEmissionsActivities"
               style="width: 80%;height: 300px"></div>
          <div>
            <p>
              量化并比较不同活动在特定时间段内的碳排放量。{{ getProjectNames }}在{{ startTime }}- {{ endTime }}中，
              {{ getActivityValueMaxIndex() === -1 ? null : activityNames[getActivityValueMaxIndex()]
              }}碳排放量最高，为{{ getActivityValueMaxIndex() === -1 ? null : activityTotals[getActivityValueMaxIndex()]
              }}
              kgCO2;
              {{ getActivityValueMinIndex() === -1 ? null : activityNames[getActivityValueMinIndex()] }}碳排放量最低，为
              {{ getActivityValueMinIndex() === -1 ? null : activityTotals[getActivityValueMinIndex()] }} kgCO2。
            </p>
            <table style="width: 100%;margin: 0">
              <thead>
              <tr>
                <th>数据时间</th>
                <th v-for="item in activityNames">{{ item }}</th>
                <th>总量</th>
              </tr>
              </thead>
              <tbody>
              <tr v-for="(item,index) in activityCarbonEmissionsData" :key="`${item.solidifyDate}_${index}`">
                <td>{{ item.solidifyDate }}</td>
                <td v-for="itemValue in item.valueList">{{ itemValue }}</td>
                <td>{{ item.total }}</td>
              </tr>
              </tbody>
            </table>
            <p>
              展示和分析在时间段内不同活动的碳排放量。{{ getProjectNames }}在 {{ startTime }}-{{ endTime }}中，
              <span v-for="(item,index) in activityNames">{{ item }}碳排放总量为
                {{ activityCarbonEmissionsData.map(dataItem => dataItem.valueList[index]).reduce((a, b) => a + b, 0)
                }} kgCO2，其中{{ getActivityValueMaxByIndex(index).solidifyDate
                }}的用电碳排放量最高，为{{ getActivityValueMaxByIndex(index).valueList[index] }} kgCO2;
              {{ getActivityValueMinByIndex(index).solidifyDate
                }}用电碳排放量最低，为{{ getActivityValueMinByIndex(index).valueList[index] }} kgCO2。</span>
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.analysis-box {
  margin: 0 5%;

  .energy-type-box, .range-box {
    display: flex;
    justify-content: space-between;
    gap: 100px;
    margin: 0 5%;
  }

  .time-carbon-emissions-box {
    margin: 0 20%;
  }

  .space-carbon-emissions-box, .analysis-carbon-emissions-activities-box {
    margin: 0 10%;
  }

  table {
    border-collapse: collapse;
    width: 60%;
    margin: 0 20%;
    font-size: 16px;
    font-weight: 500;

    th {
      border: 1px solid rgba(0, 0, 0, 0.6);
      padding: 6px 10px;
      background-color: rgb(2, 149, 144);
      text-align: center;
    }

    td {
      border: 1px solid #000000;
      padding: 6px 10px;
      text-align: center;
    }
  }

  .desc {
    margin: 0 15%;

  }

  p {
    text-indent: 2em;
    line-height: 24px;
  }
}
</style>
